package com.kancy.jemeter.functions;

import com.kancy.jemeter.util.MessageUtil;
import com.kancy.jemeter.util.RandomUtil;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author kancy
 * @date 2019/6/30 0:04
 */
public class DateTimeFunction extends JemeterAbstractFunction {
	public DateTimeFunction() {
		super(0,3);
	}

	@Override
	public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
		String format = getParameter(0, "yyyy-MM-dd HH:mm:ss");
		String floatDay = getParameter(1, "0");
		long floatMins = Math.abs(Long.parseLong(floatDay) * 24 * 60 * 60 * 1000);
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		long now = System.currentTimeMillis();
		String result = "";
		if(floatMins == 0){
			result = dateFormat.format(new Date(now));
		}else {
			result = dateFormat.format(new Date(RandomUtil.nextLong(now - floatMins, now + floatMins)));
		}
		return setJMeterVariable(2, result);
	}

	private static final List<String> argumentDesclist = new LinkedList();

	static {
		argumentDesclist.add(MessageUtil.getResString("_datetime.format.message"));
		argumentDesclist.add(MessageUtil.getResString("_datetime.float.message"));
		argumentDesclist.add(MessageUtil.getResString("varname.message"));
	}


	@Override
	public List<String> getArgumentDesc() {
		return argumentDesclist;
	}
}
